﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using VAdvantage.Grids;
using VAdvantage.Apps;
using System.Windows.Data;
using System.Collections.Generic;
using VAdvantage.Model;
using VAdvantage.Classes;
using System.Linq;

namespace VAdvantage.Controls
{
    public class VPaneItem : ATreeViewItem, IControl, IButton

    {

        #region declaration
        private bool _isReadOnly = false;
        //set control name as column name 
        private String _columnName;
        private String _text;
        //mendatory fileds
        private bool _mandatory;
        private Object _value;
        /** List of Key/Name        */
        private Dictionary<String, String> _values = null;
        //private Hashtable _values = null;
        /** Description as ToolTip  */
        private String _description = "";
        private String _help;
        //set process id
        private int _AD_Process_ID;
        //Mlookup class object
        private MLookup _lookup;
        //field object
        private GridField _field;
        //display text
        private int _displayType = 0;
        //if buttton is readonly
        private bool _readOnly;
        //private string _btnValue="";
        private SolidColorBrush brush = new SolidColorBrush();

        private Binding binding = null;

        #endregion

        public VPaneItem()
        {
            this.Margin = new Thickness(-17, 1, 0, 2);
        }

        public static readonly DependencyProperty ValueChangedProperty =
   DependencyProperty.Register("Value", typeof(Object), typeof(VAdvantage.Controls.VPaneItem), new PropertyMetadata((o, e) =>
   {
       ((VPaneItem)o).SetValue((Object)e.NewValue);

   }));
        
        public Object Value
        {
            get
            {
                return ((Object)GetValue(VPaneItem.ValueChangedProperty));
            }
            set
            {
                SetValue(VPaneItem.ValueChangedProperty, value);
            }
        }

        /// <summary>
        /// Set Atrribute of Button Used by Host DataGrdiView column
        /// </summary>
        /// <param name="columnName">Displayed column name</param>
        /// <param name="mandatory">Bool Type(mendatory status)</param>
        /// <param name="isReadOnly">Bool Type(readonly status)</param>
        /// <param name="isUpdateable">Bool type(is update able)</param>
        /// <param name="text">text</param>
        /// <param name="description">discription</param>
        /// <param name="help">Help text</param>
        /// <param name="AD_Process_ID">display process id</param>
        public void SetAttribute(GridField field, String columnName, bool mandatory, bool isReadOnly, bool isUpdateable,
                                  String text, String description, String help, int AD_Process_ID)
        {
            if (!DataBase.GlobalVariable.IsVisualEditor)
            {
                SetField(field);
                this.Header = text;
                // this.Name = columnName;//column name
                _text = text;//display text
                _columnName = columnName;
                //
                _mandatory = mandatory;//mendatory

                if (isReadOnly || !isUpdateable)
                    this.IsEnabled = false;
                else
                    this.IsEnabled = true;
                //this.
                // this.TextImageRelation = TextImageRelation.ImageBeforeText;
                //	Special Buttons
                if (columnName.Equals("PaymentRule"))
                {
                   // ReadReference(195);
                    //this.setForeground(Color.blue);
                    brush.Color = Colors.Blue;
                    this.Foreground = brush;
                    this.Icon = Utility.Envs.LoadImageSource("Payment16.jpg");    //  29*14
                }
                //else 
                if (columnName.Equals("DocAction"))
                {
                    ReadReference(135);
                    //this.setForeground(Color.blue);
                    brush.Color = Colors.Blue;
                    this.Foreground = brush;
                    //setIcon(Env.getImageIcon("Process16.gif"));    //  16*16
                    this.Icon = Utility.Envs.LoadImageSource("Process16.jpg");
                }
                else if (columnName.Equals("CreateFrom"))
                {
                    //setIcon(Env.getImageIcon("Copy16.gif"));       //  16*16
                    this.Icon = Utility.Envs.LoadImageSource("Copy16.jpg");
                }
                else if (columnName.Equals("Record_ID"))
                {
                    //setIcon(Env.getImageIcon("Zoom16.gif"));       //  16*16
                    this.Icon = Utility.Envs.LoadImageSource("Zoom16.jpg");
                    this.Header = Utility.Msg.GetMsg(Utility.Envs.GetContext(), "ZoomDocument", true);
                }
                else if (columnName.Equals("Posted"))
                {
                    ReadReference(234);
                    //this.setForeground(Color.magenta);
                    brush.Color = Colors.Magenta;
                    this.Foreground = brush;
                    this.Icon = Utility.Envs.LoadImageSource("InfoAccount16.jpg");
                }

                else
                {
                    this.Icon = Utility.Envs.LoadImageSource("button16.png");
                }
                _description = description;
                if (description == null || description.Length == 0)
                    _description = " ";
                else
                    SetToolTipText(_description);
                //
                _help = help;
                _AD_Process_ID = AD_Process_ID;

            }
            else
            {
                _field = field;
                this.Header = text;
                this.Name = columnName;//column name
                _text = text;//display text
                _columnName = columnName;
                //
                _mandatory = mandatory;//mendatory

                if (isReadOnly || !isUpdateable)
                    this.IsEnabled = false;
                else
                    this.IsEnabled = true;
                //  this.TextImageRelation = TextImageRelation.ImageBeforeText;
                if (columnName.Equals("PaymentRule"))
                {
                    // ReadReference(195);
                    //this.setForeground(Color.blue);
                    brush.Color = Colors.Blue;
                    this.Foreground = brush;
                    this.Icon = Utility.Envs.LoadImageSource("Payment16.jpg");    //  29*14
                }
                //else 
                if (columnName.Equals("DocAction"))
                {
                    //ReadReference(135);
                    //this.setForeground(Color.blue);
                    brush.Color = Colors.Blue;
                    this.Foreground = brush;
                    //setIcon(Env.getImageIcon("Process16.gif"));    //  16*16
                    this.Icon = Utility.Envs.LoadImageSource("Process16.jpg");
                }
                else if (columnName.Equals("CreateFrom"))
                {
                    //setIcon(Env.getImageIcon("Copy16.gif"));       //  16*16
                    this.Icon = Utility.Envs.LoadImageSource("Copy16.jpg");
                }
                else if (columnName.Equals("Record_ID"))
                {
                    //setIcon(Env.getImageIcon("Zoom16.gif"));       //  16*16
                    this.Icon = Utility.Envs.LoadImageSource("Zoom16.jpg");
                    this.Header = Utility.Msg.GetMsg(Utility.Envs.GetContext(), "ZoomDocument", true);
                }
                else if (columnName.Equals("Posted"))
                {
                    //ReadReference(234);
                    //this.setForeground(Color.magenta);
                    brush.Color = Colors.Magenta;
                    this.Foreground = brush;
                    //setIcon(Env.getImageIcon("InfoAccount16.gif"));    //  16*16
                    this.Icon = Utility.Envs.LoadImageSource("InfoAccount16.jpg");
                }

                _description = description;
                if (description == null || description.Length == 0)
                    _description = " ";
                else
                    SetToolTipText(_description);
                //
                _help = help;
                _AD_Process_ID = AD_Process_ID;


            }
        }

        private void SetToolTipText(string _description)
        {
            ToolTipService.SetToolTip(this, _description);
        }

        #region "Icontrol Interface "

        /// <summary>
        /// Is Mandatory
        /// </summary>
        /// <returns></returns>
        public bool GetIsMandatory()
        {
            return _mandatory;
        }

        /// <summary>
        /// Sets Mandatory
        /// </summary>
        /// <param name="value">bool type value</param>
        public void SetIsMandatory(bool value)
        {
            _mandatory = value;
        }

        /// <summary>
        /// readonly combo
        /// </summary>
        /// <returns>read only fields</returns>
        public bool GetIsReadonly()
        {
            return _readOnly;
        }

        /// <summary>
        /// field displayed
        /// </summary>
        /// <returns>field from Model.GridField class</returns>
        public GridField GetField()
        {
            return _field;
        }

        public string GetSelectedText()
        {
            return "";
        }



        /// <summary>
        /// set the control field object
        /// </summary>
        /// <param name="field">return field</param>
        public void SetField(GridField field)
        {
            _field = field;
            if (field.GetColumnName().EndsWith("_ID") && !field.GetColumnName().Equals("Record_ID"))
            {
                System.Threading.ThreadPool.QueueUserWorkItem(delegate
                {
                    _lookup = MLookupFactory.Get(Utility.Envs.GetContext(), field.GetWindowNo(),
                            field.GetAD_Column_ID(), DisplayType.Search);
                });

            }
            else if (field.GetAD_Reference_Value_ID() != 0)
            {
                System.Threading.ThreadPool.QueueUserWorkItem(delegate
                {
                    //	Assuming List
                    _lookup = MLookupFactory.Get(Utility.Envs.GetContext(), field.GetWindowNo(),
                        field.GetAD_Column_ID(), DisplayType.List);
                });
            }
        }

        /// <summary>
        /// display record
        /// </summary>
        /// <returns>display value</returns>
        public int GetDisplayType()
        {
            if (_displayType == 0)
            {
                _displayType = DisplayType.Button;
            }
            return _displayType;
        }

        /// <summary>
        /// combo display type
        /// </summary>
        /// <param name="displayType">display name</param>
        public void SetDisplayType(int displayType)
        {
            _displayType = displayType;
        }

        /// <summary>
        /// get column name
        /// </summary>
        /// <returns>return name</returns>
        public string GetName()
        {
            return this._columnName;
        }

        /// <summary>
        /// get button text
        /// </summary>
        /// <returns>Button text</returns>
        public string GetText()
        {
            return _text;
        }

        /// <summary>
        /// return selected value
        /// </summary>
        /// <returns>selected id</returns>
        public object GetValue()
        {
            //return this._AD_Process_ID.ToString();
            if (_value != null)
            {
                return _value.ToString();
            }
            else
            {
                return null;
            }
        }


        /// <summary>
        /// Set value
        /// </summary>
        /// <param name="value">value</param>
        public void SetValue(object value)
        {
            _value = value;
            string text = _text;

            //	Nothing to show or Record_ID
            if (value == null || value.ToString() == "" || _columnName.Equals("Record_ID"))
            {
            }
            else if (_values != null && _values.Count != 0)
            {
                if (_values.ContainsKey(value.ToString()))
                {
                    text = (String)_values[value.ToString()];
                }
            }
            else if (_lookup != null)
            {
                NamePair pp = _lookup.Get(value);
                if (pp != null)
                    text = pp.GetName();
            }

            //	Display it
            this.Header = text != null ? text : "";
        }

        /// <summary>
        /// for help
        /// </summary>
        /// <returns>help text</returns>
        public string GetHelp()
        {
            return _help;
        }

        /// <summary>
        /// get discription of control
        /// </summary>
        /// <returns>idscription text</returns>
        public string GetDescription()
        {
            return _description;
        }

        /// <summary>
        /// Set Isreadonly
        /// </summary>
        /// <param name="readOnly"></param>
        public void SetReadOnly(bool readOnly)
        {
            this.IsEnabled = !readOnly;
        }

        public event EventHandler VetoableChangeListener;

        public void SetName(string name)
        {
            this._columnName = name;
        }

        public void SetBackGround(bool value)
        {
            //
        }

        public bool IsDisabled()
        {
            return !this.IsEnabled;
        }

        public void SetDisabled(bool disabled)
        {
            this.IsEnabled = !disabled;
        }

        public int GetTabIndex()
        {
            return this.TabIndex;
        }

        public void SetTabindex(int tabindex)
        {
            this.TabIndex = tabindex;
        }

        public bool Multiline
        {
            get;
            set;
        }

        public bool Visible
        {
            get
            {
                return this.Visibility == System.Windows.Visibility.Visible;
            }
            set
            {
                this.Visibility = value ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
            }
        }

        public bool Focused
        {
            get { return false; }
        }


        #endregion

        public void Dispose()
        {
            brush = null;
            if (_values != null)
                _values.Clear();
            _value = null;

            if (_lookup != null)
                _lookup.Dispose();
            _lookup = null;

            binding = null;

        }

        string IControl.BindValue
        {
            set
            {
                binding = new Binding(value);
                binding.Mode = BindingMode.OneWay;
                this.SetBinding(VPaneItem.ValueChangedProperty, binding);
            }
            //set{  textArea.SetBinding(textArea.Text,  throw new NotImplementedException(); }
        }

        public int GetAD_Process_ID()
        {
            return _AD_Process_ID;
        }

        /// <summary>
        /// Fill _values with Ref_List values
        /// </summary>
        /// <param name="AD_Reference_ID">reference</param>
        private void ReadReference(int AD_Reference_ID)
        {
            _values = new Dictionary<String, String>();
            String sql = "";
            Context ctx = VAdvantage.Utility.Envs.GetContext();

            var client = Utility.AEnv.GetDataServiceClient();

            try
            {

                client.GetDataXMLCompleted += (sender, e) =>
                {
                    if (e.Error == null)
                    {
                        try
                        {
                            System.Xml.Linq.XElement ele = System.Xml.Linq.XElement.Parse(e.Result);

                            //var data = from t in ele.Descendants("Table")
                            //           select t;
                            var data = ele.Descendants("Table");
                                       

                            foreach (var dr in data)
                            {
                                String value = Utility.Util.GetValueofString(dr, "Value");
                                String name = Utility.Util.GetValueofString(dr, "Name");
                                _values.Add(value, name);
                            }
                        }

                        catch (Exception ex)
                        {

                            //Logging.VLogger.Get().Log(Logging.Level.SEVERE, sql, ex);
                        }
                    }
                };

                if (ctx.GetAD_Language() == Login.Language.GetBaseAD_Language())
                    sql = "SELECT Value, Name FROM AD_Ref_List WHERE AD_Reference_ID=" + AD_Reference_ID;
                else
                    sql = "SELECT l.Value, t.Name FROM AD_Ref_List l, AD_Ref_List_Trl t "
                        + "WHERE l.AD_Ref_List_ID=t.AD_Ref_List_ID"
                        + " AND t.AD_Language='" + ctx.GetAD_Language() + "'"
                        + " AND l.AD_Reference_ID=" + AD_Reference_ID;

                client.GetDataXMLAsync(sql);
                client.CloseAsync();
            }
            catch
            {

            }
        }

        /// <summary>
        /// Return value/name
        /// </summary>
        /// <returns>HashTable with Value/Names</returns>
        public Dictionary<String, String> GetValues()
        {
            return _values;
        }
        #region IDisposable Members

        //public void Dispose()
        //{
           
        //}

        #endregion
    }
}
